﻿using System;
using System.Windows;
using System.Globalization;
using System.Windows.Media.Imaging;

using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Manutd.Services;
using Manutd.Models;
using HtmlAgilityPack;
using GalaSoft.MvvmLight.Messaging;

namespace Manutd.ViewModel
{
    public class NewsDetailViewModel : ViewModelBase
    {
        private readonly INavigationService navigationService;
        private readonly IWebScraper webScrapingService;

        private Article article;
        private bool isLoading;
        private string articleUrl;

        public enum ContentType
        {
            Text,
            Image
        }

        public NewsDetailViewModel()
        {
            //MessengerInstance.Register<GenericMessage<string>>(this, new Action<GenericMessage<string>>(StartScrapingArticle));
            Messenger.Default.Register<string>(this, "ArticleUrl", url => StartScrapingArticle(url));
            this.navigationService = new NavigationService(((App)Application.Current).RootFrame);
            //this.webScrapingService = new WebScrapingService();

            this.Article = new Article();

            //this.LoadArticleCommand = new RelayCommand(this.LoadArticleAction);
        }

        public Article Article
        {
            get { return this.article; }
            set
            {
                if (value == null) return;
                this.article = value;
                this.RaisePropertyChanged(() => Article);
            }
        }

        public bool IsLoading
        {
            get { return isLoading; }
            set
            {
                isLoading = value;
                this.RaisePropertyChanged(() => IsLoading);
            }
        }

        //public RelayCommand LoadArticleCommand { get; private set; }

        //private void LoadArticleAction()
        //{
        //    this.StartScrapingArticle()
        //}

        public void StartScrapingArticle(string url)
        {
            IsLoading = true;
            HtmlWeb.LoadAsync(url, OnCallback);
        }

        private void OnCallback(object s, HtmlDocumentLoadCompleted e)
        {
            var loadedArticle = new Article();
            if (e.Error == null)
            {
                var htmlDoc = e.Document;

                // get article head lines
                loadedArticle.Title = htmlDoc.DocumentNode.SelectSingleNode("//h1[@itemprop='headline']").InnerText;

                // get article content
                var articleTextDiv = htmlDoc.DocumentNode.SelectSingleNode("//div[@class='article-text']");
                var innerText = articleTextDiv.InnerText;
                var innerHtml = articleTextDiv.InnerHtml;
                var startArticleNode = articleTextDiv.SelectSingleNode(".//comment()");
                var currentNode = startArticleNode.NextSibling;
                var count = 0;
                while (!currentNode.InnerText.Contains("Article End"))
                {
                    var nodeName = currentNode.Name;
                    switch (nodeName)
                    {
                        case "p":
                            if (currentNode.NextSibling.Name.Equals("img"))
                            {
                                loadedArticle.Content.Add(ContentType.Image.ToString() + "_" + count, currentNode.Attributes["src"].Value);
                            }
                            else
                                loadedArticle.Content.Add(ContentType.Text.ToString() + "_" + count, currentNode.InnerText + "\n\n");
                                //loadedArticle.Content += currentNode.InnerText + "\n\n";
                            break;
                        case "#text":
                            loadedArticle.Content.Add(ContentType.Text.ToString() + "_" + count, currentNode.InnerText);
                            //loadedArticle.Content += currentNode.InnerText;
                            break;
                        case "a":
                            loadedArticle.Content.Add(ContentType.Text.ToString() + "_" + count, currentNode.InnerText);
                            //loadedArticle.Content += currentNode.InnerText;
                            break;
                        case "br":
                            loadedArticle.Content.Add(ContentType.Text.ToString() + "_" + count, "\n");
                            //loadedArticle.Content += "\n";
                            break;
                    }
                    currentNode = currentNode.NextSibling;
                    count++;
                }

                //var pTags = articleTextDiv.SelectNodes("//p");
                //if (pTags.Count > 1)
                //{
                //    foreach (var p in pTags)
                //    {
                //        loadedArticle.Content += p.InnerText + "\n\n";
                //    }
                //}
                //else
                //{
                //    foreach (var node in articleTextDiv.ChildNodes)
                //    {
                //        if (node.Name.Equals("p"))
                //        {
                //            loadedArticle.Content += node.InnerText + "\n";
                //        }
                //        else if (node.Name.Equals("#text"))
                //        {
                //            loadedArticle.Content += node.InnerText;
                //        }
                //        else if (node.Name.Equals("a"))
                //        {
                //            loadedArticle.Content += node.InnerText;
                //        }
                //        else if (node.Name.Equals("br"))
                //        {
                //            loadedArticle.Content += "\n";
                //        }
                //        else if (node.Name.Equals("em"))
                //        {

                //        }
                //    }
                //}

                // get article author
                //loadedArticle.Author = htmlDoc.DocumentNode.SelectSingleNode("//h2[@class='author']").InnerText;

                // get article pub Date
                loadedArticle.PubDateString = htmlDoc.DocumentNode.SelectSingleNode("//time[@itemprop='datePublished']").InnerText;

                // get article images
                var imageNode = htmlDoc.DocumentNode.SelectSingleNode("//img[@class=' article-image']");
                var imageUrlString = imageNode.Attributes["src"].Value;
                var uri = new Uri(imageUrlString);
                loadedArticle.Image = new BitmapImage(uri);

                // get article source

                this.Article = loadedArticle;
                IsLoading = false;
            }
        }
    }
}
